﻿using System;
using System.Diagnostics;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using TfsComLib.TfsBranchLib2;

namespace TfsBranchLib2.View
{
    /// <summary>
    ///     Interaction logic for BranchSetControl.xaml
    /// </summary>
    public partial class BranchSetControl : UserControl
    {
        // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty BranchSetProperty =
            DependencyProperty.Register("BranchSetValue", typeof (BranchSet), typeof (BranchSetControl),
                new UIPropertyMetadata(null, OnBranchSetChanged));

        public BranchSetControl()
        {
            InitializeComponent();
        }

        public BranchSet BranchSetValue
        {
            get { return (BranchSet) GetValue(BranchSetProperty); }
            set { SetValue(BranchSetProperty, value); }
        }

        private static void OnBranchSetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            try
            {
                var branchSetControl = d as BranchSetControl;
                if (branchSetControl == null) return;
                if (branchSetControl.stackPanel == null) return;
                branchSetControl.stackPanel.Children.Clear();
                var sb = new StringBuilder();
                var isMore = false;
                var i = 0;
                var branchSet = e.NewValue as BranchSet;
                if (branchSet == null) return;
                foreach (var branch in branchSet)
                {
                    var serverPath = branch.ServerPath;
                    if (i++ < 5)
                    {
                        branchSetControl.stackPanel.Children.Add(new TextBlock {Text = serverPath, FontSize = 10});
                    }
                    else
                    {
                        isMore = true;
                    }
                    sb.AppendLine(serverPath);
                }
                if (isMore)
                {
                    branchSetControl.stackPanel.Children.Add(new TextBlock
                    {
                        Text = string.Format("<<more>> ({0} branches)", branchSet.Count),
                        FontStyle = FontStyles.Italic,
                        FontSize = 10
                    });
                    var fullList = sb.ToString();
                    branchSetControl.ToolTip = fullList.TrimEnd('\n', '\r');
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(string.Format("Branch set changed exception: {0}", ex));
                Debug.WriteLine(string.Format("Branch set changed exception: {0}", ex));
            }
        }
    }
}